package com.jcl.recruit.api.upload.controller;

import com.jcl.recruit.core.config.SpringConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 刘明新
 * @date 2018/8/9 下午2:26
 */
@RestController
public class UploadController {

    @Autowired
    private SpringConfig springConfig;

    /**
     * 文件上传具体实现方法;
     *
     * @param file
     * @return
     */
    @RequestMapping("/api/upload")
    @ResponseBody
    public Map<String,Object> handleFileUpload(@RequestParam("file") MultipartFile file) throws  Exception{
        Map<String,Object> map = new HashMap<>();
        String filePath = "/home/lamp/www/html/attach/test";
        if(springConfig.getSpringProfiles().equals("prod")){
            filePath = "/home/lamp/www/html/attach/www";
        }
        String str = new String(Base64.getEncoder().encode(file.getOriginalFilename().getBytes("UTF-8")));
        String filename = new Date().getTime() + str;
        try {
            File targetFile = new File(filePath);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(filePath + filename);
            out.write(file.getBytes());
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(filePath + filename);
        map.put("url",filePath + filename);
        map.put("filename",filename);
        return map;
    }

}
